package com.xjtu.mybatisplus.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.xjtu.mybatisplus.common.JsonResponse;
import com.xjtu.mybatisplus.common.constant.MessageConstant;
import com.xjtu.mybatisplus.common.exception.BaseException;
import com.xjtu.mybatisplus.common.utls.JwtUtil;
import com.xjtu.mybatisplus.common.utls.Producer;
import com.xjtu.mybatisplus.common.utls.SensitiveFilter;
import com.xjtu.mybatisplus.model.domain.Comment;
import com.xjtu.mybatisplus.mapper.CommentMapper;
import com.xjtu.mybatisplus.model.vo.comment.CommentsVo;
import com.xjtu.mybatisplus.service.CommentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lsong
 * @since 2023-12-27
 */
@Service
@Slf4j
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {

    @Value("${jwt.user-token-name}")
    private String tokenName;

    @Autowired(required = false)
    private CommentMapper commentMapper;

    @Autowired
    private SensitiveFilter sensitiveFilter;

    @Autowired
    private Producer producer;
    @Override
    public boolean addComment(Comment comment, HttpServletRequest request) {
        String token = request.getHeader(tokenName);
        if(token == "" || token == null){
            return false;
        }
        // 获取登陆的用户信息
        Long userId = JwtUtil.getFrontUserId(token);
        if(userId == null){
            return false;
        }
        // 对敏感词进行过滤
        comment.setContent(sensitiveFilter.filter(comment.getContent()));
        comment.setUserId(userId);
        comment.setIsDeleted(0);
        comment.setCreateTime(LocalDateTime.now());
        log.info("传入的评论为{}",comment);
        try {
            producer.produceMessage(comment);
        } catch (Exception e){
            log.info("加入队列失败：{}",e.getMessage());
            save(comment);
        }
        return true;
    }

    @Override
    public List<CommentsVo> getCommentByArticalId(Integer id) {

        // TODO 如何进行SQL优化
        List<CommentsVo> resp = commentMapper.queryByArticalId(id);
//        List<CommentsVo> resp = new ArrayList<>();
//        QueryWrapper<Comment> wrapper = new QueryWrapper<>();
//        wrapper.eq("article_id",id)
//                .eq("top_father_id",0)
//                .eq("father_id",0)
//                .eq("is_deleted",0);
//        List<Comment> comments = commentMapper.selectList(wrapper);
//        for(Comment comment : comments){
//        }
        return resp;
    }

    @Override
    public void deleteByCommentId(Long id, Long userId) {
        Comment comment = commentMapper.selectById(id);
        if(comment.getUserId() != userId){
            return;
        }
        recursiveLogicDeleteById(id);
    }

    public void recursiveLogicDeleteById(Long id) {
        List<Long> commentIdsToDelete = getRecursiveCommentIdsToDelete(id);
        if (!commentIdsToDelete.isEmpty()) {
            commentMapper.recursiveLogicDelete(commentIdsToDelete);
        }
    }
    private List<Long> getRecursiveCommentIdsToDelete(Long id) {
        // 递归查询评论的 ID，可以使用递归查询的 SQL 语句，这里简化为示例
        List<Long> commentIds = commentMapper.selectRecursiveCommentIds(id);
        return commentIds;
    }
}
